package org.glutenberg;
import java.io.IOException;
import java.util.Vector;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import org.glutenberg.dao.HandbookDAO;
import org.glutenberg.dao.ProductReader;
import org.glutenberg.dao.ReverseIndex;
import org.glutenberg.util.CollectionUtils;
import org.glutenberg.util.StringComparator;

import com.sun.lwuit.Display;
import com.sun.lwuit.Form;

public class Handbook extends MIDlet {

	private HandbookDAO dao;
	private Results results;
	private FindForm search;
	private Error error;
	private NotFound notFound;
	private About about;
	private Vector lastSearch;
	private ProductReader lastProductReader;
	private static StringComparator comparator = new StringComparator();

	public static void printUsedMemory(){
		System.out.println(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
	}
	
	protected void startApp() throws MIDletStateChangeException {

		Display.init(this);
		this.error = new Error(this);
		try {
			this.about = new About(this);
			this.results = new Results(this);
			this.search = new FindForm(this);
			this.notFound = new NotFound(this);
			this.initFileConnection();
			this.find();			
		} catch (Throwable t) {
			this.error.setError(t.toString());
			this.error.show();
		}
	}
	
	private void initFileConnection() throws IOException{
		this.dao = new HandbookDAO();
	}
	
	public void quit(){
		try {
			this.destroyApp(true);
		} catch (MIDletStateChangeException e) {
			e.printStackTrace();
		} finally {				
			this.notifyDestroyed();
		}		
	}
	
	
	public void showResults(Vector keywords) throws IOException{
		keywords = ReverseIndex.prepareWords(keywords);
		if(this.lastSearch==null || CollectionUtils.compareVectors(this.lastSearch, keywords, comparator)!=0){
			ProductReader reader = this.dao.search(keywords, false);
			this.lastProductReader = reader;
			this.lastSearch = keywords;
			if(reader!=null && reader.size()>0){
				this.results.setProductReader(reader);
			}
		}
		if(this.lastProductReader!=null && this.lastProductReader.size()>0){
			this.results.show();
		} else {
			this.notFound.show();
		}
	}
	
	public void find() {
		this.search.show();
	}
	
	public void about(Form previous) {
		this.about.setPrevious(previous);
		this.about.show();
	}

	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {}

	protected void pauseApp() {}
}
